import { Injectable } from '@nestjs/common';
import { CreateChatDto } from './dto/create-chat.dto';
import { UpdateChatDto } from './dto/update-chat.dto';
import { UserInfoDto } from '../model/dto/user-info.dto';

import { User } from '../user/entities/user.entity';
import { ChatSchemaService } from '../../services/chat-schema/chat-schema.service';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Response } from 'express';

interface DifyContent {
  inputs: Record<string, any>;
  query: string;
  response_mode: "blocking" | "streaming";
  conversation_id?: string;
  user?: unknown;
  files: any[];
}

interface ChatResponse {
  answer: string;
  conversation_id?: string;
  [key: string]: any;
}

@Injectable()
export class ChatService {
  constructor(
    @InjectRepository(User)
    private userRepository: Repository<User>
  ) {
  }

  async create(
    createChatDto: CreateChatDto,
    user?: UserInfoDto
  ): Promise<Record<string, any>> {

    const message = createChatDto.message
    const host = process.env.KNOWLEDGE_BASE_HOST;
    const chatApiKey = process.env.KNOWLEDGE_BASE_CHAT_API_KEY;

    // 获取conversation_id
    let conversationId;
    if (user?.id) {
      const existingUser = await this.userRepository.findOneBy({ id: user.id });
      conversationId = existingUser?.conversation_id || '';
    }

    // 用户输入消息
    const query = message;

    // dify会话入参
    const difyContent: DifyContent = {
      inputs: {},
      query,
      response_mode: "blocking",
      conversation_id: conversationId,
      user: user?.id,
      files: []
    };

    const response = await fetch(`${host}/v1/chat-messages`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${chatApiKey}`
      },
      body: JSON.stringify(difyContent)
    });
    // 模型返回结果
    if (!response.ok) {
      const errorData = await response.json();
      console.error('API request failed:', errorData);
      return { error: errorData.message || 'Request failed' };
    }
    const data: ChatResponse = await response.json();

    //更新user表
    const exitUser = await this.userRepository.findOneBy({ id: user?.id })
    if (exitUser) {
      exitUser.conversation_id = data.conversation_id as string;
      await this.userRepository.save(exitUser);
    }

    // 输出结果
    let parsedAnswer: Record<string, any>;
    parsedAnswer = JSON.parse(data.answer);

    return parsedAnswer;

  }

  async findAll() {
    return `This action returns all chat`;
  }

  findOne(id: number) {
    return `This action returns a #${id} chat`;
  }

  update(id: number, updateChatDto: UpdateChatDto) {
    return `This action updates a #${id} chat`;
  }

  remove(id: number) {
    return `This action removes a #${id} chat`;
  }
}
